/**
 * Created by jf on 2015/9/11.
 * Modified by bear on 2016/9/7.
 */
//ui
// M_WIDTH = 750;
isMobile = function(){
    var e = $(document).width()<1024
    return e;
}
cookie = {
    value:null,
    init:function(){
        this.value = {};
        var c = document.cookie.split(";")
        for(var i in c){
            var v = c[i].split("=");
            cookie.value[v[0].replace(" ","")] = v[1];
        }
    },
    get:function(k){
        return cookie.value[k];
    },
    set:function(key,content,second){
        if(!key || !content) return false;
        if(!second) second = 7*24*60*60;
        var exp = new Date();
        exp.setTime(exp.getTime() + second*1000);
        document.cookie = key + "="+ escape(content) + ";expires=" + exp.toGMTString();
        this.init();
    },
    delete:function(key){
        this.set(key,1,-1);
    }
}
lang = {
    init:function(){
        this.apply();
        if(langIsZh) return;
        $(window).on('page-success',function(event) {
            lang.apply();
        });
    },
    apply:function(){
        if(cookie.get('langIsNotZh')){
            langIsZh = false;
        }else{
            langIsZh = navigator.language.indexOf('zh') > -1;
        }
        $(".hidden-zh,.hidden-en").removeClass('hidden');
        if(langIsZh){
            $(".hidden-zh").addClass('hidden');
        }else{
            var lang = "en"
            $("[lang-"+lang+"]").each(function(index, el) {
                var e = $(el)
                var trans = e.attr("lang-"+lang);
                if(!trans) return true;
                if(e.attr("placeholder")){
                    e.attr('placeholder',trans);
                }else if(e.attr("type")=="submit"){
                    e.val(trans);
                    e.html(trans)
                }else{
                    e.html(trans)
                }
            });
            $(".hidden-en").addClass('hidden');
        }
    },
    setEnglish:function(){
        cookie.set('langIsNotZh',1);
        this.apply();
    },
    setChinese:function(){
        cookie.delete('langIsNotZh');
        location.reload();
    },
}
error = {
    top:function(action,errormsg){
        var $tooltips = $('.js_tooltips');
        if(!$tooltips || !$tooltips.length){
            $('body').prepend("<div class='weui-toptips weui-toptips_warn js_tooltips'></div>");
            $tooltips = $('.js_tooltips');
        }
        $tooltips.css('display', 'none');
        $tooltips.fadeToggle();
        $tooltips.fadeIn();
        if(action == "0"){
            var text = "没有网络";
        }else{
            var text = action || "";
            if(action){ text+=langIsZh?"失败:":" error:"}
            text += errormsg;
        }
        $tooltips.html(text);
        var i = parseInt( $tooltips.attr("data-index") || 0 ) + 1 ;
        $tooltips.attr("data-index",i);
        setTimeout(function () {
            var ii = parseInt( $tooltips.attr("data-index") || 0 ) ;
            if( ii != i ) return;
            $tooltips.css('display', 'block');
            $tooltips.fadeOut();
        }, 3000);
    }
}
value = {
    loading:function(t,key){
        if(!t || !t.length){
            return;
        }
        t.find("["+key+"]").each(function(index, el) {
            var e = $(el);
            var tag = e[0].tagName.toLowerCase();
            if(tag == 'input' || tag == 'textarea' || tag == 'select'){
                e.after("<i class='weui-loading'></i>");
                e.hide();
                return
            }
            switch(e.attr(key)){
                case "f":
                case "1":
                e.html("<i class='weui-loading'></i>");
                break;
                case "r":
                e.children().first().siblings().remove();
                case "i":
                // return
                e.children().hide();
                e.append("<i class='weui-loading'></i>");
                break;
                case "d":
                // return
                e.children().hide();
                e.append("<i class='weui-loading'></i>");
                break;
            }
        });
    },
    write:function(e,key,v){
        // console.log('write',e,key,v)
        // alert(v)
        if(!e || !e.length){
            return;
        }
        if(v == null || v == 'null') v = "";
        var tag = e[0].tagName.toLowerCase();
        if(tag == 'input' || tag == 'textarea' || tag == 'select'){
            switch(e.attr("type")){
                case "checkbox":
                var c = v;
                if(c == "0") c = false;
                e.prop("checked",c)
                break;
                case "radio":
                // console.error(e,e.val(),v)
                e.prop("checked",(e.val() == v))
                break;
                default:
                e.val(v);
            }
            e.fadeIn();
            e.siblings('.weui-loading').remove();
            return
        }
        e.find('.weui-loading').remove();
        switch(e.attr(key)){
            case "1":
            // console.log(e,v)
            if(typeof(v) == 'object') v = JSON.stringify(v);
            e.html(v);
            break;
            case "f":
            vv = ((v/100).toFixed(2) + '').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
            // console.log(vv,v,isNaN(v));
            if(isNaN(v)) vv = '0.00';
            e.html(vv);
            break;
            case "i":
            if(!e.children('img').length){
                e.append("<img />");
            }
            var img = e.children('img')
            img.attr({src:v})
            img.siblings().remove()
            img.show();
            break;
            case "d":
            e.children(".weui-loading").remove();
            if(v && v != "0"){
                e.children().show();   
            }else{
                e.children().hide();  
            }
            break;
            case "r":
            if(e.find("[range='body']").length) e = e.find("[range='body']");
            // console.log(v)
            if(!v) return;
            if(typeof(v) != "object") v = eval("("+v+")");
            var tmp = e.find("[range='template']");
            if(tmp.length){
                var template_html = tmp.prop('outerHTML');
                tmp.remove();
            }else{
                // console.log(e.children().first());
                var template_html = e.children().first().prop('outerHTML');
                e.html(template_html);
                e.children().first().hide();
            }
            for(var kk in v){
                var vv = v[kk];
                var line_html = template_html
                for(var kkk in vv){
                    var vvv = vv[kkk];
                    line_html = line_html.replace(eval("/__"+kkk+"__/g"),vvv)
                }
                e.append(line_html);
                var newline = e.children().last()//$(template_html);
                for(var kkk in vv){
                    var vvv = vv[kkk];
                    // newline.html(newline.html().replace(eval("/__"+kkk+"__/g"),vvv))
                    // console.log($template.find(kkk+"[range],[name='"+kkk+"'][range]"),vvv);
                    newline.find(kkk+"[range],[name='"+kkk+"'][range]").each(function(index, el) {
                        value.write($(el),'range',vvv);
                    });
                    // $hh.find(kkk).html(vvv);
                }
                newline.show();
                // e.append($template);
                // e.children().last().show();
            }
            break;
        }
        e.fadeIn();
    }
}
user = {
}
timer = {
    expiring:function(t){
        var t = $(t);
        var tm = t.find("timer");
        var res = tm.length > 0;
        return res;
    },
    complete:function(t){
        t.find("timer").remove();
        t.removeClass('weui-btn_disabled');
    },
    expire:function(t){
        var t = $(t);
        var tm = t.find("timer");
        if(!tm.length) return;
        var n = parseInt(tm.children().html());
        if(n>0){
            var tt = (n-1)?1000:150
            tm.children().html(n-1);
            setTimeout(function(){
                timer.expire(t);
            },tt);
        }else{
            this.complete(t);
        }
    },
    start:function(t,expirdIn){
        if(isNaN(parseInt(expirdIn))) return;
        var t = $(t);
        var tm = t.find("timer");
        if(!tm.length){
            t.append('<timer>(<t>'+expirdIn+'</t>)</timer>');
            tm = t.find("timer");
            setTimeout(function(){
                timer.expire(t);
            },1000);
        }else{
            tm.children().html(expirdIn);
        }
        if(t.hasClass('weui-btn') || t.hasClass('weui-vcode-btn')){
            t.addClass('weui-btn_disabled');
        }
    }
}
toast = {
    template:'<div class="toast" style="display:none;"><div class="weui-mask_transparent"></div><div class="weui-toast"><i class="weui-icon weui-icon-success-no-circle weui-icon weui-icon_toast"></i><i class="weui-loading weui-icon weui-icon_toast"></i><p class="weui-toast__content"></p></div></div>',
    load:function(html,fullhtml){
        var tt = $(".toast");
        if( !tt || !tt.length ){
            $("body").append(this.template);
            tt = $(".toast");
        }
        tt.fadeIn(100,function(){
            tt.removeAttr('style');
        });
        // tt.find(".weui-loading").show()
        // tt.show();
        var icon = tt.find("i.weui-loading");
        var content = tt.find(".weui-toast__content");
        icon.removeAttr('style');
        icon.siblings('i').hide();
        if(fullhtml){
            content.html(html);
        }else{
            content.html((langIsZh?"正在":"")+html);
        }
    },
    error:function(){
        var tt = $(".toast");
        tt.fadeOut();
    },
    stop:function(){
        var tt = $(".toast").fadeToggle().hide();
    },
    success:function(html,fullhtml){
        var tt = $(".toast");
        if( !tt || !tt.length ){
            $("body").append(this.template);
            tt = $(".toast");
        }
        var icon = tt.find("i.weui-icon-success-no-circle")
        var content = tt.find(".weui-toast__content");
        icon.removeAttr('style');
        icon.siblings('i').hide();
        if(fullhtml){
            content.html(html);
        }else{
            content.html(html+(langIsZh?"成功":" success"));
        }
        if( tt.css('display') == "none" ){
            tt.fadeIn(100,function(){
                tt.removeAttr('style');
            });
        }
        setTimeout(function(){
            tt.fadeOut(300);
        },500);
    }
}
post = {
    animate:{
        start:function(p){
            var $e = p.e
            console.log(" ---- BC-POST ("+(p.index)+") TRIGGER ---- ",$e,"bc.post.start")
            if($e.length) $e.trigger("start");
            if($e.length) $e.trigger("bc.post.start");
            switch(p.style){

                case 0://default
                toast.load(p.text);
                break;

                case 1://input
                var cell = $e.closest(".weui-cell__bd,.weui-cell__hd,.weui-cell__ft")
                var label = cell.siblings().children("label").first()
                if(!label || !label.length) label = cell.children("label").first();
                if(label && label.length){
                    p.e.attr("data-index",p.index+1);
                    if( label.css("display") == "none" ) return;
                    cell.siblings('.weui-cell__ft').children(".weui-icon").remove();
                    label.children(".weui-icon").remove();
                    var c = label.attr('class');
                    label.after('<label><small mute>'+p.text+'中...</small></label>')
                    var a = label.next();
                    a.addClass(c);
                    label.hide();
                    return
                }
                var title = $e.parents(".weui-cells").prev(".weui-cells__title").children("label").first();
                if(title && title.length){
                    title.attr("data-index",p.index+1);
                    title.removeClass('weui-cell_warn')
                    if( title.css("display") == "none" ) return;
                    title.children(".weui-icon").remove();
                    var c = title.attr('class');
                    title.after('<label><small mute>'+p.text+'中...</small></label>')
                    var a = title.next();
                    if(c) a.addClass(c);
                    title.hide();
                    return
                }
                case -1://none;
                return;
                break;
            }
        },
        clean:function(p,isError){
            var $e = p.e
            var cell = $e.closest(".weui-cell__bd,.weui-cell__hd,.weui-cell__ft")
            var label = cell.siblings().children("label").first()
            if(!label || !label.length) label = cell.children("label").first();
            var index = parseInt( p.e.attr("data-index") || 0 ) ;
            var title = $e.parents(".weui-cells").prev(".weui-cells__title").children("label").first();
            if(title && title.length){
                var index = parseInt( title.attr("data-index") || 0 ) ;
            }
            if(index != p.index + 1 ) return;
            if(label && label.length){
                label.next("label").remove();
                label.show();
                if(isError){
                    label.parents('.weui-cell').addClass('weui-cell_warn');
                    if(!$e.parents(".weui-cell_select").length) $e.parent().siblings('.weui-cell__ft').append('<small class="bc-post-error weui-icon weui-icon-warn"></small>')
                }else{
                    label.parents('.weui-cell').removeClass('weui-cell_warn');
                    label.prepend('<small class="bc-post-success weui-icon weui-icon-success weui-icon-original"></small> ')
                    label.find(".weui-icon-success").hide().fadeIn('slow');
                }
                return
            }
            if(title && title.length){
                title.next("label").remove();
                title.show();
                if(isError){
                    title.addClass('weui-cell_warn')
                    title.prepend('<small class="bc-post-error weui-icon weui-icon-error"></small>')
                }else{
                    title.removeClass('weui-cell_warn')
                    title.prepend('<small class="bc-post-success weui-icon weui-icon-success weui-icon-original"></small>')
                }
            }

        },
        success:function(p){
            $e = p.e
            console.log(" ---- BC-POST ("+p.index+") TRIGGER ---- ",$e,"success")
            $e.trigger("success");
            $e.trigger("post-success");
            if($e.hasClass('weui-btn_disabled')) $e.removeClass('weui-btn_disabled');
            switch(p.style){
                case 0:
                toast.success(p.text);
                break;
                case 1://input
                // console.log('clean');
                this.clean(p);
                case -1://none;
                return;
                break;
            }
        },
        error:function(p){
            $e = p.e
            if($e && $e.length){
                console.log(" ---- BC-POST ("+p.index+") TRIGGER ---- ",$e,"post-error",p.errormsg)
                $e.trigger("post-error",p.errormsg);
                var index = $e.attr("data-index") || 0;
                if($e.hasClass('weui-btn_disabled')) $e.removeClass('weui-btn_disabled');
                switch(p.style){
                    case 0:
                    toast.error();
                    break
                    case 1://input
                    // console.log('clean');
                    this.clean(p,true);
                    break;
                    case -1://none;
                    return;
                    break;
                    default:
                }
            }
            error.top(p.text,p.errormsg);
        }
    },
    styles:{0:0,input:1,none:-1},
    init:function(e,c,target){
        var $e = $(e);
        if($e.hasClass('bc-post')) return;
        $e.addClass('bc-post');
        var method = c.method || 'click';
        var style = c.style || 0;
        var style = this.styles[style];
        var text = c.text || "处理"
        var msg = c.msg || {};
        $e.each(function(index, el) {
            var $e = $(el);
            $e.on(method,target,function(event){
                $e = $(this);
                if(c.stop && c.stop($e,event)){
                    event.preventDefault();
                    return;
                }
                if(c.confirm){
                    var data_confirm = c.confirm(this,event)
                    var str = data_confirm.text || text;
                    str = "确认"+str;
                    if(data_confirm.target) str += " ["+ data_confirm.target +"] ";
                    if(!confirm(str+"?")) return;
                }
                if($e.hasClass('bc-posting')||$e.hasClass('weui-btn_disabled')) return;
                if($e.hasClass('weui-btn') || $e.hasClass('weui-vcode-btn')) $e.addClass('weui-btn_disabled');
                // $e.addClass('bc-posting');
                var index = parseInt( $e.attr("data-index") || 0 );
                var title = $e.parents(".weui-cells").prev(".weui-cells__title").children("label").first();
                if(title && title.length){
                    var index = parseInt( title.attr("data-index") || 0 );
                }
                var url = c.url || '/test/getlist';
                if(url== "/test/getlist"){
                    console.error($e,"test-port");
                }
                if(c.input || false){
                    var data = c.input(this,event);
                }else{
                    var data = {}
                    var name = $(this).attr("name");
                    // console.log("name",name)
                    if(name){
                        data['key'] = name;
                        switch($(this).attr("type")){
                            case "radio":
                            if($(this).prop("checked")) data['value'] = $(this).val();
                            break;
                            case "checkbox":
                            data['value'] = $(this).prop("checked");
                            break;
                            default:
                            data['value'] = $(this).val();
                            break;
                        }
                    }

                }
                //post.start
                post.animate.start({e:$e,style:style,text:text,index:index});
                console.log(" ---- BC-POST ("+index+") ---- ",url,data)
                $.ajax({
                    type:"post",
                    url:url,
                    data:data,
                    success:function(ret){
                        console.log(" ---- BC-POST ("+index+") RETURN ---- ",ret)
                        $e.removeClass('bc-posting');
                        ret = ret || {}
                        if(!ret || !ret.state ){
                            var errormsg = ret.errormsg
                            if(langIsZh){
                                var errormsg_text = msg[errormsg] || errormsg;
                            }else{
                                var errormsg_text = errormsg
                            }
                            // var errormsg_cn = msg[errormsg] || errormsg;
                            //post.error
                            post.animate.error({e:$e,style:style,text:text,errormsg:errormsg_text,index:index});
                            if(c.error) c.error($e,ret);
                            return
                        }
                        //post.success
                        post.animate.success({e:$e,style:style,text:text,index:index});
                        if(c.success) c.success($e,ret);
                    },
                    error:function(xhr){
                        var errormsg = xhr.statusText + " " + xhr.status ;
                        $e.removeClass('bc-posting');
                        //post.error
                        post.animate.error({e:$e,style:style,text:text,errormsg:errormsg,index:index});
                        if(c.error) c.error($e,{errormsg:errormsg});
                    }
                })
            })
        })
    }
}
detail = {
    content:{},
    init:function(t){
        var d = $(t).find(".bc-list-detail,.bc-detail");
        this.put(d);
    },
    put:function(d){
        var d = $(d).closest('.bc-list-detail,.bc-detail');
        if(!d || !d.length){
            return false;
        }
        d.find(".bc-post-error,.bc-post-success").remove();
        d.find(".weui-cell_warn").removeClass('weui-cell_warn');
        var content = detail.content;
        d.find("[detail]").each(function(index, el) {
            var e = $(el);
            var key = e[0].tagName.toLowerCase();
            if(key=="input" || key=="textarea" || key=="select"){
                key = $(el).attr("name");
            }
            if(!content || !content.length){
                var v = "";
            }else{
                var v = content.find(key).html();
            }
            value.write(e,"detail",v)
            // console.log(" ---- BC-DETAIL TRIGGER ---- ",e,"bc.detail.success")
            // e.trigger("bc.detail.success");
        });
        d.find(".bc-btn-group").each(function(index, el) {
            btn_group.select(el);      
        });
        d.find(".bc-list").each(function(index, el) {
            list.reload(el);
        });
    },
    clean:function(t){
        var d = $(t).closest(".bc-list-detail,.bc-detail");
        if(!d || !d.length){
            return false;
        }
        detail.content = $();
        detail.put(d);
    }
}
info = {
    $info:null,
    ids:{},
    page:null,
    errorhtml:'<div class="weui-msg bc-info-error"><div class="weui-msg__icon-area"><i class="weui-icon weui-icon-warn weui-icon weui-icon_msg"></i></div><div class="weui-msg__text-area"><h2 class="weui-msg__title">内容无法获取</h2><p class="weui-msg__desc"><reason></reason></p></div></div>',
    errorhtmlSimple:'<span class="weui-icon weui-icon-warn weui-icon-original">?<span>',
    loadinghtml:'<div class="weui-msg bc-info-loading"><div class="weui-msg__icon-area"><i class="weui-icon weui-icon-waiting weui-icon weui-icon_msg"></i></div><div class="weui-msg__text-area"><h2 class="weui-msg__title"><i class="weui-loading"></i>加载中</h2><p class="weui-msg__desc"><reason></reason></p></div></div>',
    loadinghtmlSimple:"<i class='weui-loading'></i>",
    init:function(t){
        var i = $(t).find(".bc-list-info,.bc-info");
        if(!i || !i.length){
            return false;
        }
        var url = location.hash.indexOf('#') === 0 ? location.hash.replace("#","").split("/") : null ;
        if(url){
            var page = url[0];
        }else{
            var page = "home";
        }
        if(url && url.length > 1){
            var ids = url[1];
        }else{
            var ids = "";
        }
        var ids_old = this.ids[page];
        if( ids_old == ids ) return false;
        this.ids[page] = ids;
        this.page = page;
        i.each(function(index, el) {
            if(!$(el).hasClass('no-init') && $(el).css('display') != "none" ){
                info.reload(el);
            }
            if($(el).hasClass('bc-info-click-reload')){
                $(el).on('click', function(event) {
                    info.reload(this);
                    event.preventDefault();
                });
            }
        });
    },
    error:function(t,index,reason){
        if(!t.trigger) return;
        t.find("[info]").each(function(i, el) {
            var e = $(el)
            value.write(e,"info",null);
        });
        console.log(" ---- BC-INFO ("+index+") TRIGGER ---- ",t,"info-error",reason);
        t.trigger("error",reason)
        t.trigger("info-error",reason)
        switch(t.attr('data-error')){
            case 'post':
            post.animate.error({errormsg:reason});
            return;
            break;
        }
        if(!t.hasClass('bc-list-info') && t.find("[info]").length == 0){
            t.html(this.errorhtmlSimple.replace("?",reason)); return;
        }
        if(t.hasClass('bc-info')) return;
        t.hide();
        t.after(this.errorhtml).next().find('reason').html(reason);
    },
    input:function(){
        var t = this.$info;
        if(!this.page){
            this.error("page error");
            return false;
        }
        var ids = this.ids[this.page];
        if(t.hasClass('bc-list-info') && !ids){
            this.error("url id missing");
            return false;
        }
        ids = ids.split("|");
        var keys = this.$info.attr("data-keys");
        if(!keys){
            keys = "id";
        }
        keys = keys.split(",");
        var data = {}
        for( var i in keys){
            if(ids.length > i && ids[i]) data[keys[i]] = ids[i];
        }
        if(!data.length) return null;
        return data;
    },
    put:function(t,$info){
        this.$info = t = $(t).closest('.bc-info,.bc-list-info');
        t.find("[info]").each(function(index0, el) {
            var e = $(el);
            var key = e[0].tagName.toLowerCase();
            if(key=="input" || key=="textarea" || key=="select"){
                key = $(el).attr("name");
            }
            var v = $info[key];
            value.write(e,"info",v)
            t.trigger("data")
        });
        var index = t.attr("data-index");
        console.log(" ---- BC-INFO ("+index+") TRIGGER ---- ",t,"success",t.find("[info]"))
        t.trigger("success",$info);
        t.trigger("info-success",$info);
        // if(showLoading) 
        if(t.css("display")=='none') t.fadeToggle().fadeIn(501);
    },
    reload:function(t, data){
        this.$info = t = $(t).closest('.bc-info,.bc-list-info');
        if(!t || !t.length) return;
        var showLoading = !t.hasClass("bc-info")
        var simple = t.find("[info]").length?false:true;
        if(simple){
            t.html(this.loadinghtmlSimple);
        }
        t.next(".bc-info-error").remove();
        if(showLoading) t.hide();
        var content = t.attr("data-content");
        if(content){
            var info_content = eval(content).info;
            if(info_content){
                this.put(t,info_content);
                return
            }
        }
        // console.log(t);
        var port = t.attr("data-port") || "/test/info";
        if(port == '/test/info'){
            console.error(t,"test-port");
        }
        if(!port){
            this.error("port error")
            return
        }
        if(!data) data = this.input();
        if(t.hasClass('.bc-list-info') && data === false){
            return
        }
        if(showLoading) t.after(this.loadinghtml)
            var index = parseInt( t.attr("data-index") || 0 ) + 1;
        t.attr("data-index",index);
        console.log(" ---- BC-INFO ("+index+") ---- ",port,data)
        console.log(" ---- BC-INFO ("+index+") TRIGGER ---- ",t,"start")
        t.trigger("start");
        t.trigger("info-start");
        value.loading(t,"info")
        $.ajax({
            url: port,
            data: data,
            // dataType: 'json',
            success:function(ret){
                var index2 = parseInt( t.attr("data-index") || 0 ) ;
                if( index2 != index ) return;
                console.log(" ---- BC-INFO ("+index+") RETURN ---- ",typeof(ret),ret)
                t.next(".bc-info-loading").remove();
                if(typeof(ret) == 'string'){
                    t.html('');
                    t.html(ret);
                    t.fadeIn();
                    return
                }
                if(!ret.state){
                    info.error(t,index,ret.errormsg);
                    return
                }
                var $info = ret.data.info;
                if(!$info){
                    info.error(t,index,"info missing");
                    return
                }
                if(simple){
                    var key = t.attr('info');
                    var v = ret.data.info[key];
                    // console.log(ret,key)
                    t.html(v);
                    console.log(" ---- BC-INFO ("+index+") TRIGGER ---- ",t,"info-success",v)
                    t.trigger("success",v);
                    t.trigger("info-success",v);
                    return
                }
                if(content) eval(content).info = $info;
                info.put(t,$info)
            },
            error:function(xhr, type){
                var index2 = parseInt( t.attr("data-index") || 0 ) ;
                if( index2 != index ) return;
                t.next(".bc-info-loading").remove();
                info.error(t,index,xhr.statusText + " " + xhr.status )
            }
        })
    }
}
list = {
    $list:{
        loadTemplate:{
            error:"<div onclick='list.reload(this)' class='bc-list-loadmore weui-loadmore weui-loadmore_line'><span class='weui-loadmore__tips' style=color:maroon>code</span></div>",
            loading:"<div class='bc-list-loadmore weui-loadmore'><i class='weui-loading'></i><span class='weui-loadmore__tips'>正在加载</span></div>",
            empty:"<div class='bc-list-loadmore weui-loadmore weui-loadmore_line'><span class='weui-loadmore__tips'>暂无内容</span></div>",
            nomore:"<div class='bc-list-loadmore weui-loadmore weui-loadmore_line weui-loadmore_dot'><span class='weui-loadmore__tips'></span></div>",
            loadmore:"<div onclick='list.loadmore(this)' align='center' class='bc-list-loadmore weui-panel__ft'><a href='javascript:void(0);' class='weui-cell weui-cell_access weui-cell_link'><div class='weui-cell__bd' style='padding:8px;'>加载更多</div></a></div>"
        }
    },
    init:function(){
        $(document).on('change','.bc-list', function(event) {
            e = $(event.target);
            if(e.closest('.bc-list-template,.bc-list-content,.bc-btn-group').length){
                return true;
            }
            list.reload(e);
        });
    },
    pageInit:function(t){
        if(!this.find(t)){
            return false;
        }
        var l = this.$list;
        l.edit.on('click', function(event) {
            list.closest(this)
            var t = $(this)
            var l = list.$list;
            // console.log(l,t)
            if(t.hasClass('active')){
                t.children().text("编辑")
                t.removeClass('active')
                l.checkbox.hide();
                l.menu.hide();
                l.link.fadeIn(1100);
                l.content.children().removeClass('editing');
            }else{
                t.children().text("完成")
                t.addClass('active')
                l.checkbox.find("input[type='checkbox']").prop('checked',false);
                l.checkbox.fadeIn();
                l.menu.fadeIn(1100);
                l.link.hide();
                l.content.children().addClass('editing');
            }
        });
        l.selectAll.on('click', function(event) {
            list.selectAll(this);
        });
        l.selectReverse.on('click', function(event) {
            list.selectReverse(this);
        });
        l.bar.each(function(index, el) {
            list.reload(el);
        });
        if(false && !weixin.is() && isMobile() && l.menu && l.menu.length){
            var page = l.bar.closest('.page')
            var menu = page.find(".bc-list-menu").parents(".weui-cell").eq(0);
            page.attr({"data-menu-top":menu.offset().top})
            page.on('scroll',function(){
                var h = $(this).attr("data-menu-top");
                var s = $(this).scrollTop();
                // h = parseInt(h);
                if(s>h){
                    menu.addClass('weui-cell-top');
                }else{
                    menu.removeClass('weui-cell-top');
                }
            })
        }
        //
    },
    selectAll:function(t){
        if(t) this.closest(t);
        this.$list.checkbox.find("input[type='checkbox']").prop("checked",true);
    },
    selectReverse:function(t){
        if(t) this.closest(t);
        this.$list.checkbox.find("input[type='checkbox']").each(function(i,n){
            $(n).prop('checked',!$(n).is(":checked"));
        })
    },
    selected:function(t){
        if(t) this.closest(t);
        var ids = []
        this.$list.checkbox.find("input:checked").each(function(index, el) {
            var new_id = $(el).closest('[data-id]').attr('data-id');
            if(new_id) ids.push(new_id);
        });
        return ids;
    },
    ids:function(t){
        if(t) this.closest(t);
        var ids = []
        this.$list.content.children().each(function(index, el) {
            var id = $(el).attr("data-id");
            if(id) ids.push(id);
        });
        return ids;
    },
    input:function(t){
        if(t) this.closest(t);
        var input = {};
        var l = this.$list;
        l.bar.find("input,textarea,select").not(".bc-list-template *,.bc-btn-group *").each(function(index, el) {
            e = $(el)
            switch(e.prop('type')){
                case "radio":
                if(e.prop('checked')){
                    input[e.prop('name')] = e.val()
                }
                break;
                case "checkbox":
                if(e.prop('checked')){
                    input[e.prop('name')] = true;
                }
                break;
                default:
                if(e.prop('name') && e.val().length){
                    input[e.prop('name')] = e.val()
                }
                break;
            }
        });
        input['page'] = parseInt(l.page)+1;
        // console.log(input)
        return input;
    },
    reload:function(t,data){
        if(t) this.closest(t);
        // this.$list.loadmore.remove();
        // console.log($(t),this.$list)
        if(this.$list.content && this.$list.content.length){
            if(this.$list.content.height()>23){
                this.$list.content.css({height:this.$list.content.height()});
            }
            this.$list.content.html("");
            if(!this.$list.nomore){
                this.$list.content.append(this.$list.loadTemplate.loading)
            }
        }else{
            // console.log(this.$list.template);
            if(!this.$list.nomore){
                this.$list.template.after(this.$list.loadTemplate.loading)
            }
        }
        this.$list.bar.removeAttr('page');
        this.$list.page = 0;
        this.ajax(t,data);
    },
    loadmore:function(t){
        if(t) this.closest(t);
        if(!this.$list.nomore){
            this.$list.loadmore.remove();
            this.$list.content.after(this.$list.loadTemplate.loading)
        }
        this.ajax();
    },
    ajax:function(t,data){
        var tt = this
        var l = this.$list
        // console.log(l)
        // return;
        var bar = l.bar
        if(!data) var data = this.input();
        var dataId = this.$list.dataId;
        var url = l.port;
        var content = l.content
        var template = l.template.eq(0)
        var template_html = l.t
        var portIndex = parseInt(l.portIndex)+1;
        if(!l.content || !l.content.length){
            template_class = template.prop("class").replace("bc-list-template","");
            template_tag = template.prop("tagName");
            content_html = "<"+template_tag+" class='"+template_class+" bc-list-content'></"+template_tag+">";
            template.before(content_html)
            tt.$list.content = l.content = content = bar.find(".bc-list-content")
        }else{
            // alert(l.content.prop("outerHTML"))
        }
        bar.attr({'data-port-index':portIndex});
        template.hide();
        console.log(" ---- BC-LIST ("+portIndex+") ---- ",url,data)
        console.log(" ---- BC-LIST ("+portIndex+") TRIGGER ---- ",bar,"start")
        bar.trigger("start")
        $.ajax({
            url: url,
            data: data,
            success: function(ret){
                console.log(" ---- BC-LIST ("+portIndex+") RETURN---- ",ret)
                if( parseInt(bar.attr('data-port-index')) != portIndex ){
                    return
                }
                bar.find('.bc-list-loadmore').remove();
                if(!ret.state){
                    var errormsg = ret.errormsg + " " + (bar,ret.errorcode||"");
                    list.error(bar,errormsg);
                    console.log(" ---- BC-LIST ("+portIndex+") TRIGGER ---- ",bar,"error",errormsg)
                    bar.trigger("error",errormsg)
                    return
                }
                var c = ret.data.list;
                if(!c){
                    content.after(l.loadTemplate.empty);
                    content.removeAttr('style')
                    return false;
                }
                bar.attr('data-page',parseInt(l.page)+1)
                var length = parseInt(content.children().length);
                var n = 0;
                for( i in c ){
                    var d = c[i];
                    if(dataId){
                        exist = content.children("[data-id='"+d[dataId]+"']")
                        if(exist && exist.length){
                            continue;
                        }
                    }
                    content.append(template_html);
                    line = content.children().eq(length+parseInt(n))
                    // console.log('d[dataId]',d[dataId])
                    line.attr({'data-id':d[dataId]})
                    line.addClass('bc-list-new').hide();
                    line.addClass('bc-list-line');
                    var detailBox = line.append('<div class="bc-list-detail-box"></div>').find(".bc-list-detail-box").hide();
                    for(var k in d ){
                        line.find(k+"[list],[name='"+k+"'][list]").each(function(index, el) {
                            var e = $(el);
                            var v = d[k];
                            value.write(e,"list",v)
                            // console.log(" ---- BC-LIST ("+portIndex+") TRIGGER ---- ",e,"value")
                            e.trigger("value")
                        });
                        var v = d[k];
                        if(typeof(v) == "object"){
                            // v = jQuery.parseJSON(v);
                            v = JSON.stringify(v);
                        }
                        if(v == null || v == 'null') v = "";
                        // if(d[k])
                        detailBox.append("<"+k+" list=1>"+v+"</"+k+">");
                    }
                    n++;
                    // console.log(" ---- BC-LIST ("+portIndex+") TRIGGER ---- ",line,"line")
                    line.trigger("line")
                }
                content.children(".bc-list-new").on('click', function(event) {
                    detail.content = $(this).find(".bc-list-detail-box");
                    // console.log('put',detail.content)
                    if($(this).hasClass('editing')){
                        event.preventDefault();
                        box = $(this).find(".bc-list-checkbox input");
                        box.prop("checked",!box.prop('checked'))
                    }else{
                        // event.preventDefault();
                        if($(this).attr('href')) eval($(this).attr('href'));
                    }
                });
                content.children(".bc-list-new").removeClass('bc-list-new').fadeIn(1000);
                content.removeAttr('style')
                content.find(".bc-list-checkbox").hide();
                l.edit.children().text("编辑")
                l.edit.removeClass('active')
                l.checkbox.hide();
                l.menu.hide();
                if(!l.nomore){
                    if(ret.data.more){
                        content.after(l.loadTemplate.loadmore);
                    }else{
                        content.after(l.loadTemplate.nomore);
                    }
                }
                console.log(" ---- BC-LIST ("+portIndex+") TRIGGER ---- ",bar,"success")
                bar.trigger("success")
                bar.trigger("list-success")
            },
            error: function(xhr, type){
                list.error(bar,xhr.statusText+" "+xhr.status);
            }
        })
    },
    error:function(bar,msg){
        var content = bar.find('.bc-list-content')
        content.removeAttr('style')
        bar.find('.bc-list-loadmore').remove();
        if(content && content.length){
            var a = content
        }else{
            var a = bar.find(".bc-list-template")
        }
        a.after(list.$list.loadTemplate.error.replace('code',msg));
    },
    detail:function(t){

    },
    find:function(t){
        t = $(t).find('.bc-list')
        if(!t.length){
            return false;
        }
        return this.$(t);
    },
    closest:function(t){
        t = $(t).closest('.bc-list')
        if(!t.length){
            return false;
        }
        return this.$(t);
    },
    $:function(t){
        this.$list = {loadTemplate:this.$list.loadTemplate}
        this.$list.bar = t;
        if(!t){
            return false;
        }
        this.$list.portIndex         = t.attr("data-port-index") || parseInt(100*Math.random())*1000;
        this.$list.port              = t.attr("data-port") || "/test/getlist";
        if(this.$list.port == "/test/getlist"){
            console.error(t,"test-port");
        }
        this.$list.page              = t.attr("data-page") || 0;
        this.$list.dataId            = t.attr("data-id") || "id";
        this.$list.template          = t.find(".bc-list-template");
        this.$list.t                 = t.find(".bc-list-template").html();
        this.$list.content           = t.find(".bc-list-content");
        this.$list.loadmore          = t.find(".bc-list-loadmore");
        this.$list.selectAll         = t.find(".bc-list-select-all");
        this.$list.selectReverse     = t.find(".bc-list-select-reverse");
        this.$list.edit             = t.find(".bc-list-edit");
        this.$list.menu             = t.find(".bc-list-menu");
        this.$list.link             = t.find(".bc-list-link");
        this.$list.checkbox         = t.find(".bc-list-content .bc-list-checkbox");
        this.$list.nomore           = t.attr("nomore") || 0;
        return true;
    }
}
rank = {
    $rank:null,
    init:function(t){
        // console.log(t);
        var r = $(t).find(".bc-rank");
        r.each(function(index, el) {
            rank.reload(el);    
        });
    },
    error:function(t,errormsg){
        var portIndex = 0;
        console.log(" ---- BC-RANK ("+portIndex+") TRIGGER ---- ","error",errormsg)
        t.trigger("error",errormsg)
        t.trigger("rank-error",errormsg)
        // post.animate.error({errormsg:errormsg})
    },
    reload:function(t,data){
        var t = $(t).closest('.bc-rank');
        if(!t || !t.length) return;
        //界面处理
        t.find(".bc-rank-content,.bc-rank-error").remove();
        var template = t.find(".bc-rank-template");
        template.hide();
        //接口访问
        var url = t.attr("data-port") || "/test/rank";
        if(url == '/test/rank'){
            console.error(t,"test-port");
        }
        var data = data || {};
        $.ajax({
            url: url,
            data:data,
            success:function(ret){
                t.find(".bc-rank-content,.bc-rank-error").remove();
                console.log(" ---- BC-RANK ("+0+") TRIGGER ---- ",t,"rank-start",ret)
                t.trigger("rank-start")
                // console.error(ret);
                if(!ret.state){
                    var errormsg = ret.errormsg;
                    rank.error(t,errormsg)
                    return
                }
                if(!ret.data || !ret.data.rank){
                    var errormsg = "rank missing";
                    rank.error(t,errormsg)
                    return
                }
                var res = ret.data.rank;
                var template_html = template.prop("outerHTML").replace(/bc-rank-template/g,"bc-rank-content");
                for( var i in res){
                    var v = res[i]
                    var content_html = template_html;
                    // console.error(typeof(v))
                    switch(typeof(v)){
                        case "string":
                        content_html = content_html.replace(/__value__/g,v);
                        template.parent().append(content_html);
                        break;
                        case "object":
                        template.parent().append(content_html.replace(/__key__/g,i));
                        var newrank = template.parent().children().last();
                        rank.put(newrank,v);
                        break;
                        for(kk in v){
                            var vv = v[kk];
                            // content_html = content_html.replace(eval("/__"+vv+"__/g"),vv);
                        }
                        break;
                    }
                    // template.parent().append(content_html);
                    // var newrank = template.parent().children().last();

                }
                template.siblings('.bc-rank-content').fadeIn();
                console.log(" ---- BC-RANK ("+0+") TRIGGER ---- ",t,"rank-success")
                t.trigger("success")
                t.trigger("rank-success")
            },
            error:function(xhr){
                var errormsg = xhr.statusText + " " + xhr.status
                rank.error(t,errormsg);
            }
        });
    },
    range:function(d,v){
        var tmp = d.html();
        for(var i in v){
            var c = v[i]
            d.append(tmp)
            var d_new = d.children().last();
            for( k in c){
                cc = c[k]
                switch(typeof(cc)){
                    case "object":
                    break;
                    default:
                    d_new.find(k+",[name='"+k+"'],[rank='"+k+"']").each(function(index, el) {
                        var e = $(el)
                        value.write(e,'rank',cc);
                        e.val(cc);
                    });
                    d_new.show();
                }
            }
        }
    },
    put:function(d,v){
        for(var i in v){
            var c = v[i]
            switch(typeof(c)){
                case "object":
                var dd = d.find("[bc-rank='"+i+"']")
                rank.range(dd,c);
                break;
                default:
                d.find("[name='"+i+"'],"+i+"[rank]").each(function(index, el) {
                    var e = $(el);
                    value.write(e,"rank",c);
                })
                break;
            }
        }
    }
}
modal = {
    init:function(){
        $(window).on('click', '[data-toggle="modal"]:not(.weui-btn_disabled)', function(event) {
            var k = $(this).attr('data-target');
            var m = $(k+".modal")
            var d = $(this).closest('.bc-modal-data')
            modal.open(m,d);
            event.preventDefault();
            /* Act on the event */
        });
        $(window).on('click', '[data-dismiss="modal"]', function(event) {
            modal.close($(this).closest('.modal'));
            event.preventDefault();
            /* Act on the event */
        });
        $(window).on('click touchend', '.modal-backdrop', function(event) {
            modal.close($(this).closest('.modal'));
            event.preventDefault();
            /* Act on the event */
        });
        $(document).keydown( function(e){
            if(e.which == '27' ) $(".modal").hide();
        });
    },
    toggle:function(m){
        var m = $(m)
        if(!m || !m.length) return;
        m.fadeToggle().fadeOut(0,function(){
            $(".page__body").removeClass('no-blur');
            $('body').removeAttr('style');
        });
    },
    close:function(m){
        var m = $(m)
        if(!m || !m.length) return;
        m.trigger("modal-close");
        m.fadeToggle().fadeOut(100,function(){
            $(".page__body").removeClass('no-blur');
            $('body').removeAttr('style');
        });
    },
    resize:function(m){
        var m = $(m)
        var d = m.find(".modal-dialog");
        var h = d.height()
        var hh = $(window).height();
        var mg = ( hh - h - 100 ) / 2;
        if(mg<50) mg = 50;
        // console.log(h,hh,mg)
        d.css('margin-top',mg);
    },
    open:function(m,data){
        var m = $(m)
        if(!m || !m.length) return;
        $(".modal").hide();
        if(data && data.length){
            m.find("[modal]").each(function(index, el) {
                var e = $(el)
                var kk = e.attr("name") || e[0].tagName.toLowerCase();
                var vv = data.find("[name='"+kk+"']").val() || data.find(kk).html() || "";
                value.write(e,'modal',vv);
            });
        }
        m.trigger('modal-start');
        var d = m.find(".modal-dialog");
        var backdrop = m.find(".modal-backdrop");
        if(!backdrop || !backdrop.length){
            m.prepend('<div class="modal-backdrop"></div>');
        }
        m.fadeToggle().fadeIn(100);
        $(".page__body").addClass('no-blur');
        this.resize(m);
        $('body').css('overflow','hidden')
        m.trigger('modal-success');
    }
}
tab = {
    init:function(){
        $(window).on('click touchend', '.bc-tab .bc-tab-menu>label', function(event) {
            var self = $(this)
            var tab = self.parents('.bc-tab');
            var index = self.index()
            var content = tab.find(".bc-tab-content");
            self.addClass('active');
            self.siblings().removeClass('active');
            content.children().hide();
            content.children().eq(index).fadeIn();
            // console.log(content,content.children(),content.children().eq(index),index)
            // event.preventDefault();
            /* Act on the event */
        });
    }
}
extra = {
    init:function(){
        this.fastClick();
        this.wxJSAPI();
        this.androidInputBugFix();
        this.preload();
        this.formFobbid();
        this.logout();
        this.inputTextCount();
    },
    inputTextCount:function(){
        $(window).on("keyup paste","input,textarea",function(){
            var c = $(this).next(".weui-textarea-counter")
            if(c){
                var l = parseInt($(this).val().length);
                var m = parseInt(c.find("max").html())
                c.find("span").html(l);
                if( l > m ){
                    c.css({color:"maroon"})
                }else{
                    c.css({color:"inherit"})
                }
            }
        })
    },
    logout:function(){
        $(window).on('click', '#logout', function(event) {
            if(!confirm("确认退出登录？")) return;
            event.preventDefault();
            $.ajax({
                url: '/logout',
                success:function(ret){
                    if(!ret.state) return;
                    $("#logout").trigger("success");
                    toast.success("成功安全退出",1)
                }
            })
        });
    },
    formFobbid:function(){
        $(window).on('submit', 'form', function(event) {
            event.preventDefault();
        });
    },
    fastClick:function(){
        var supportTouch = function(){
            try {
                document.createEvent("TouchEvent");
                return true;
            } catch (e) {
                return false;
            }
        }();
        var _old$On = $.fn.on;

        $.fn.on = function(){
            if(/click/.test(arguments[0]) && typeof arguments[1] == 'function' && supportTouch){ // 只扩展支持touch的当前元素的click事件
                var touchStartY, callback = arguments[1];
                _old$On.apply(this, ['touchstart', function(e){
                    touchStartY = e.changedTouches[0].clientY;
                }]);
                _old$On.apply(this, ['touchend', function(e){
                    if (Math.abs(e.changedTouches[0].clientY - touchStartY) > 10) return;

                    e.preventDefault();
                    callback.apply(this, [e]);
                }]);
            }else{
                _old$On.apply(this, arguments);
            }
            return this;
        };
    },
    androidInputBugFix:function (){
        // .container 设置了 overflow 属性, 导致 Android 手机下输入框获取焦点时, 输入法挡住输入框的 bug
        // 相关 issue: https://github.com/weui/weui/issues/15
        // 解决方法:
        // 0. .container 去掉 overflow 属性, 但此 demo 下会引发别的问题
        // 1. 参考 http://stackoverflow.com/questions/23757345/android-does-not-correctly-scroll-on-input-focus-if-not-body-element
        //    Android 手机下, input 或 textarea 元素聚焦时, 主动滚一把
        if (/Android/gi.test(navigator.userAgent)) {
            window.addEventListener('resize', function () {
                if (document.activeElement.tagName == 'INPUT' || document.activeElement.tagName == 'TEXTAREA') {
                    window.setTimeout(function () {
                        document.activeElement.scrollIntoViewIfNeeded();
                    }, 0);
                }
            })
        }
    },
    preload:function(){
        return
        $(window).on("load", function(){
            var imgList = [
            // "./images/layers/content.png",
            // "./images/layers/navigation.png",
            // "./images/layers/popout.png",
            // "./images/layers/transparent.gif"
            ];
            for (var i = 0, len = imgList.length; i < len; ++i) {
                new Image().src = imgList[i];
            }
        });
    },
    wxJSAPI:function (){
        if(!weixin.is()) return;
        $.getJSON('/wechat/jsapi?url=' + encodeURIComponent(location.href.split('#')[0]), function (res) {
            wx.config({
                // beta: true,
                // debug: true,
                appId: res.appId,
                timestamp: res.timestamp,
                nonceStr: res.nonceStr,
                signature: res.signature,
                jsApiList: [
                'scanQRCode'
                    // 'onMenuShareTimeline',
                    // 'onMenuShareAppMessage',
                    // 'onMenuShareQQ',
                    // 'onMenuShareWeibo',
                    // 'onMenuShareQZone',
                    // 'setNavigationBarColor',
                    // 'setBounceBackground'
                    ]
                });
            wx.ready(function () {
                $(window).trigger('wxready');
                // alert(123);
            });
        });
    }
}
page = {
    container:$('#container'),
    default:"home",
    stack:[],
    url:null,
    exist:function(url){
        for( var i in this.stack ){
            if( this.stack[i].url == url ) return true;
        }
        return false
        return $("[page_id='"+url+"']").length > 0;
    },
    id:function(){
        var h = location.hash.replace("#","").split("/");
        if(h.length){
            return h[1];
        }
        return null;
    },
    getHtml:function(url){
        return $('script[type="text/html"]#tpl-'+url).html().replace(/<sss>/g,"<script>").replace(/<\/sss>/g,"</script>");
    },
    getUrl:function(){
        var url = this.url
        if(url) return url
            var h = location.hash.replace("#","").split("/")
        if(!h.length){
            url = this.default;
        }else{        
            url = h[0]
        }
        if(url == ""){
            url = this.default;
        }
        if($('script[type="text/html"]#tpl-'+url).length == 0){
            url = this.default;
        }
        return url
    },
    init:function(){
        $(function(){
            page.go()            
        })
        window.pageManager = {}
        window.pageManager.go = window.go = function(url){
            location.hash = url;
        }
        window.pageManager.remove = function(url){
            page.remove(url);
        }
        window.pageManager.home = window.home = function(){
            if( page.getUrl() == page.default ){
                return
            }
            page.stack=[];
            page.url=null;
            page.container.html('');
            location.hash = page.default ;
        }
        $(window).on('hashchange', function () {
            page.url=null;
            if(page.exist(page.getUrl())){
                page.back();
            }else{
                page.go();
            }
        });
    },
    go:function(){
        $(window).scrollTop(0);
        var url = this.getUrl();
        $("[page_id='"+url+"']").remove()
        if(!isMobile()){
            $("[page_id]").not("[page_id='"+url+"']").hide();
        }else{
        }
        var html = this.getHtml(url);
        var dom = $(html).addClass(url).attr("page_id",url);
        this.container.append(dom);
        if(isMobile()){
            dom.addClass('slideIn')
            // dom.on('animationend webkitAnimationEnd', function(e){
                // dom.removeClass('slideIn').addClass('js_show');
            // });
            setTimeout(function(){
                dom.removeClass('slideIn').addClass('js_show');
            },300)  
        }else{ 
            // console.log(dom)
            dom.hide();
            dom.fadeIn(300,function(){
                dom.addClass('js_show');
            })
        }
        if(this.stack.length){
            var old = this.stack[this.stack.length-1].dom
            old.addClass('slideOutLeft');
            // old.on('animationend webkitAnimationEnd', function(){
                // old.removeClass('slideOutLeft');
            // });
            setTimeout(function(){
                old.removeClass('slideOutLeft');
            },300) 
        }
        this.stack.push({url:url,dom:dom});
        rank.init(dom);
        list.pageInit(dom);
        detail.init(dom);
        info.ids[url] = null;
        info.init(dom);
        if(isMobile()){
        	dom.append($(".footer-xs").html());
            // dom.find('.page__ft').last().html($(".footer-xs").html());
            // dom.find('.page__ft').last().children().addClass('visible-xs');
            // if(url == 'home'){
                // dom.prepend($(".header .container").html());
                // dom.children().first().addClass('visible-xs');
            // }
            // if(url == 'menu'){
                // dom.prepend('<div class="close"><a onclick="window.home();" href="javascript:void(0)"><i class="weui-icon weui-icon-close"></i></a></div>');
            // }
        }else{
            // if(url != this.default){
            //     if(this.stack.length>1){
            //         dom.find(".page__body").last().prepend('<div class="close"><a href="javascript:void(0)" onclick="history.back()"><i class="weui-icon hidden-xs weui-icon-back"></i></a></div>');
            //     }else{
            //         dom.find(".page__body").last().prepend('<div class="close"><a href="javascript:void(0)" onclick="window.home();" class=""><i class="weui-icon weui-icon-close"></i></a></div>')
            //     }
            // }
            $('body,html').scrollTop(0)
        }
        // console.log(dom,"page-success");
        dom.trigger("page-success");
    },
    back:function(){
        var old = this.stack.pop();
        if(old.url == this.getUrl()){
            this.go();
            return;
        }
        var old = $('[page_id="'+old.url+'"]');
        if(isMobile()){
            old.addClass('slideOut')
            // old.on('animationend webkitAnimationEnd', function () {
            //     old.remove();
            //     page.url = null;
            //     var url = page.getUrl();
            //     if(isMobile){
            //     }else{
            //         $("[page_id='"+url+"']").fadeIn(300);
            //     }
            // })
            setTimeout(function(){
                old.remove();
                page.url = null;
                var url = page.getUrl();
                if(isMobile()){
                }else{
                    $("[page_id='"+url+"']").fadeIn(300);
                }
            },300)
            if(page.stack.length){
                var back = page.stack[page.stack.length-1].dom
                back.addClass('slideInLeft')
                // .on('animationend webkitAnimationEnd', function(){
                    // back.removeClass('slideInLeft')
                // });
                setTimeout(function(){
                    back.removeClass('slideInLeft');
                },300) 
            }
        }else{
            old.fadeOut(100,function(){
                old.remove();
                if(page.stack.length){
                    var back = page.stack[page.stack.length-1].dom
                    back.fadeIn(100)
                }
            })
        }
    },
    remove:function(url){
        // return this._remove(url);
    // },
    // _remove:function(url){
        if(!url || !url.length) return;
        var stack = null;
        for(var i in this.stack){
            if(url == this.stack[i].url){
                stack = this.stack.splice(i,1)
                stack = stack[0];
                break;
            }
        }
        if(!stack) return;
        stack.dom.remove();
    }
}
weixin = {
    is:function(){   
        return (window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == 'micromessenger')
    },
    init:function(){
        if(!weixin.is()) return;
        document.write('<script src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>');
    },
    login:function(){
        if(!weixin.is()) return;
        toast.stop();
        toast.load("微信安全登陆",1);
        url=window.location.pathname+window.location.hash
        url='/wechat/redirect?url='+url.replace("#","{XXXXX}")
        location.href=url
    },
    share:function(){
        if(!weixin.is()) return;
        wx.onMenuShareTimeline({
            title: s.title, // 分享标题
            desc: s.desc, // 分享标题
            link: window.location.href, // 分享链接
            imgUrl: s.imgurl, // 分享图标
        });
        wx.onMenuShareAppMessage({
            title: s.title, // 分享标题
            desc: s.desc, // 分享标题
            link: window.location.href, // 分享链接
            imgUrl: s.imgurl, // 分享图标
        });
        wx.onMenuShareQQ({
            title: s.title, // 分享标题
            desc: s.desc, // 分享标题
            link: window.location.href, // 分享链接
            imgUrl: s.imgurl, // 分
        });
        wx.onMenuShareWeibo({
            title: s.title, // 分享标题
            desc: s.desc, // 分享标题
            link: window.location.href, // 分享链接
            imgUrl: s.imgurl, // 分
        });
        wx.onMenuShareQZone({
            title: s.title, // 分享标题
            desc: s.desc, // 分享标题
            link: window.location.href, // 分享链接
            imgUrl: s.imgurl, // 分
        });

    }
}
btn_group = {
    init:function(){
        $(window).on("change",".bc-btn-group *",function(){
            var self = $(this).closest('.bc-btn-group')
            if(!self || !self.length) return true;
            btn_group.put(self);
        })
    },
    put:function(e){
        self = $(e);
        var target = self.attr("data-target");
        var input;
        if(target){
            input = $(target);
        }
        if(!input){
            input = self.next("input")
        }
        if(!input) return true;
        var values = []
        self.find("input:checked").not(".bc-rank-template *").each(function(index, el) {
            var e = $(el)
            var value = e.val();
            if(!value || value == 'on') value = e.siblings('.bc-btn-group-value').html();
            if(value) values.push(value); 
            // console.log($(el))
        });
        var value = values.join(",");
        input.val(value);
        input.trigger("change")
    },
    select:function(e){
        self = $(e);
        var target = self.attr("data-target");
        var input;
        if(target){
            input = $(target);
        }
        if(!input){
            input = self.next("input")
        }
        if(!input) return true;
        var val = input.val();
        if(!val) return true;
        val = val.split(",");
        self.find("input:checked").not(".bc-rank-template *").each(function(index, el) {
            $(el).prop("checked",false);
        })
        for( var i in val ){
            var vv = val[i];
            var selector = "input[value='"+vv+"']";
            var input = self.find(selector)//.siblings('input');
            // console.log(selector,checkbox);
            if(input) input.prop("checked",true);
        }
    }
}
img_group = {}
cookie.init();
weixin.init();
lang.init();   
$(function(){
    list.init();
    modal.init();
    tab.init();
    page.init();
    extra.init(); 
    btn_group.init();
})
